package com.example.social.viewmodel

import android.content.Context
import android.net.Uri
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.social.api.ApiClient.userApiService
import com.example.social.api.BaseResponse
import com.example.social.api.LoginRequest
import com.example.social.api.RegisterModel
import com.example.social.model.UserModel
import com.example.social.utils.SharedPref
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.toRequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.FileNotFoundException
import java.io.InputStream
import java.util.UUID

class AuthViewModel : ViewModel() {

    private val _RegisterState = MutableLiveData<Int>()
    val registerState: LiveData<Int> get() = _RegisterState

    private val _error = MutableLiveData<String>()
    val error: LiveData<String> get() = _error

    private val _errorShown = MutableLiveData(false)
    val isErrorShown: LiveData<Boolean> get() = _errorShown

    // 设置错误信息
    fun setError(message: String) {
        _error.value = message
        _errorShown.value = false // 每次设置新错误时重置
    }

    // 标记错误信息已经显示
    fun markErrorAsShown() {
        _errorShown.value = true
    }


    // 登录用户
    fun login(email: String, password: String, context: Context) {
        val request = LoginRequest(email, password)
        userApiService.login(request).enqueue(object : Callback<BaseResponse<UserModel>> {
            override fun onResponse(
                call: Call<BaseResponse<UserModel>>,
                response: Response<BaseResponse<UserModel>>
            ) {
                if (response.isSuccessful) {
                    val user = response.body()?.data
                    if (user != null) {
                        saveUserData(UserModel(
                            email=user.email,
                            username = user.username,
                            nickname = user.nickname!!,
                            bio = user.bio,
                            imageurl = user.imageurl,
                            uid = user.uid
                            ), context)
                        setError("登录成功!")
                        _RegisterState.postValue(response.body()?.code)
                    } else {
                        setError("登录失败：获取用户数据为空")
                    }
                } else {
                    val errorMsg = response.body()?.msg ?: "登录失败，请重试"
                    _error.postValue(errorMsg)
                    Log.e("AuthViewModel login", "获取用户信息失败: ${response.errorBody()?.string()}")
                }
            }

            override fun onFailure(call: Call<BaseResponse<UserModel>>, t: Throwable) {
                setError("网络请求失败，请检查网络连接")
                Log.e("AuthViewModel login", "请求失败", t)
            }
        })
    }

    // 保存用户数据到 SharedPreferences
    private fun saveUserData(userModel: UserModel, context: Context) {
        SharedPref.storeData(
            userModel.nickname!!,
            userModel.email,
            userModel.bio,
            userModel.username,
            userModel.imageurl,
            userModel.uid,
            context
        )
    }

    // 注册用户
    fun register(
        email: String,
        password: String,
        nickName: String,
        bio: String,
        userName: String,
        imageUri: Uri,
        context: Context
    ) {
        viewModelScope.launch {
            // 上传头像，若失败则直接返回
            val avatarUrl = uploadAvatar(imageUri, UUID.randomUUID().toString(), context)

            if (avatarUrl == null) {
                setError("头像上传失败，请重试")
                return@launch
            }

            val userRequest = UserModel(
                email = email,
                password = password,
                nickName = nickName,
                bio = bio,
                username = userName,
                imageUrl = avatarUrl.toString()
            )
            Log.e(" response.body()?.data " , userRequest.toString())
            // 注册用户
            userApiService.registerUser(userRequest).enqueue(object : Callback<BaseResponse<String>> {
                override fun onResponse(
                    call: Call<BaseResponse<String>>,
                    response: Response<BaseResponse<String>>
                ) {
                    if (response.isSuccessful) {
                        response.body()?.let { body ->
                            _RegisterState.postValue(body.code)
                            setError(body.msg)
                        } ?: setError("注册失败：服务器返回空数据")
                    } else {
                        val errorMsg = response.body()?.msg ?: "注册失败，请重试"
                        _error.postValue(errorMsg)
                        Log.e("register", "注册失败：$errorMsg")
                    }
                }

                override fun onFailure(call: Call<BaseResponse<String>>, t: Throwable) {
                    setError("网络请求失败，请检查网络连接")
                    Log.e("register", "注册请求失败", t)
                }
            })
        }
    }


    private fun getInputStreamFromUri(uri: Uri, context: Context): InputStream? {
        return try {
            context.contentResolver.openInputStream(uri)
        } catch (e: FileNotFoundException) {
            Log.e("getInputStreamFromUri", "文件未找到: ${e.message}")
            null
        }
    }

    private suspend fun uploadAvatar(imageUri: Uri?, userId: String, context: Context): String? {
        val inputStream = imageUri?.let { getInputStreamFromUri(it, context) } ?: return null
        val requestBody = inputStream.readBytes().toRequestBody("image/jpeg".toMediaType())
        // 使用 UUID 生成唯一的文件名
        val uniqueFileName = "avatar_${UUID.randomUUID()}.jpg"
        val body = MultipartBody.Part.createFormData("file", uniqueFileName, requestBody)
        val response = userApiService.uploadAvatar(body)

        return if (response.isSuccessful) {
            response.body()?.data // 返回图片 URL
        } else {
            Log.e("uploadAvatar", "上传失败: ${response.code()} - ${response.message()}")
            null
        }
    }


    fun logout(context: Context, callback: () -> Unit) {
        val call = userApiService.logout()
        call.enqueue(object : Callback<Void> {
            override fun onResponse(call: Call<Void>, response: Response<Void>) {
                if (response.isSuccessful) {
                    //由于 callback 需要在网络请求成功/失败后调用,
                    // 不能将本地存储写在网络请求外部,
                    // 这样会导致未等网络请求结束,就直线去清空数据了
                    // 且回调也不会成功
                    Log.e(
                        "AuthViewModel logout",
                        "注销用户信息成功"
                    )
                    // 清除用户数据和状态
                    SharedPref.cleanData(context)
                    setError("登出成功!")
                    // 调用回调函数
                    callback()
                } else {
                    Log.e(
                        "AuthViewModel logout",
                        "注销用户信息失败: ${response.errorBody()?.string()}"
                    )
                    // 调用回调函数，即使在失败时也可以选择回调
                    callback()
                }
            }

            override fun onFailure(call: Call<Void>, t: Throwable) {
                // 处理请求失败的情况
                Log.e("网络请求失败 AuthViewModel logout", "网络请求失败: ${t.message}")
                // 在网络失败的情况下调用回调
                callback()
            }
        })
    }

}




//init {
    //获取当前用户信息
//        getCurrentUser()
//}

//    private fun getCurrentUser() {
//        val call = userApiService.getCurrentUser()
//        call.enqueue(object : Callback<BaseResponse<UserModel>> {
//            override fun onResponse(
//                call: Call<BaseResponse<UserModel>>,
//                response: Response<BaseResponse<UserModel>>
//            ) {
//                if (response.isSuccessful) {
//                    val users = response.body()?.data
//                    if (users != null) {
//                        // 更新当前用户数据
//                        _currentUser.postValue(users)
//                        _error.postValue(response.body()!!.msg)
//                    }
//                } else {
//                    _error.postValue(response.body()!!.msg)
//                    // 处理获取用户失败的情况
//                    Log.e(
//                        "AuthViewModel getCurrentUser",
//                        "获取用户信息失败: ${response.errorBody()?.string()}"
//                    )
//                }
//            }
//
//            override fun onFailure(call: Call<BaseResponse<UserModel>>, t: Throwable) {
//                Log.e("AuthViewModel getCurrentUser", "请求失败", t)
//            }
//        })
//    }
